package at.bartinger.gameoflive;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.DisplayMetrics;
import android.util.Log;

public class GameOfLiveRenderer {

	private int paddingx;
	private int paddingy;

	private int cellsize;
	private int screenwidth;
	private int screenheight;

	public int rows;
	public int colums;

	public double zoomfactor = 1;

	public boolean drawInfo = false;
	public int generation;

	private Paint mPaint = new Paint();
	private Paint text = new Paint();

	public GameOfLiveRenderer(int cellsize, DisplayMetrics dm) {
		this.cellsize = cellsize;
		screenwidth = dm.widthPixels;
		screenheight = dm.heightPixels;
		rows = dm.widthPixels/cellsize;
		colums = dm.heightPixels/cellsize;

		//paddingx = (screenwidth-(rows*cellsize))/2;
		//paddingy = (screenheight-(colums*cellsize))/2;

		Log.d("Game of Life","H: "+ paddingx + ", W: " +paddingy);

		mPaint.setStrokeWidth(2);
		mPaint.setColor(Color.BLACK);

		text.setColor(Color.BLUE);
		text.setTextSize(16);
		text.setFakeBoldText(true);
	}

	public void drawFrame(Canvas c, boolean[][] cells){
		drawGrid(c);
		drawCells(c,cells);
		if(drawInfo)
			drawInfo(c);
	}

	private void drawCells(Canvas c, boolean[][] cells){
		for(int x = 0; x < cells.length; x++){
			for(int y = 0; y < cells[0].length; y++){
				if(cells[x][y]){
					int cx = (int)(x*cellsize*zoomfactor)+paddingx;
					int cy = (int)(y*cellsize*zoomfactor)+paddingy;
					
					c.drawRect(cx, cy, (int)(cx+(cellsize*zoomfactor))+paddingx, (int)(cy+(cellsize*zoomfactor))+paddingy, mPaint);
				}
			}
		}
	}

	private void drawGrid(Canvas c){
		int icell;
		for(int i = 1; i <= rows; i++){//Aufteilung der Zeilen
			icell =(int) (i*cellsize*zoomfactor);
			c.drawLine(icell+paddingx, 0, icell+paddingy, screenheight, mPaint);
		}
		for(int i = 1; i <= colums; i++){//Aufteilung der Spalten
			icell =(int) (i*cellsize*zoomfactor);
			c.drawLine(0,icell+paddingx,screenwidth,icell+paddingy, mPaint);
		}
	}

	private void drawInfo(Canvas c){
		c.drawText("Generation: "+ generation , 20, 20, text);
	}

	public void setCellsize(int cellsize){
		this.cellsize = cellsize;
		rows = screenwidth/cellsize;
		colums = screenheight/cellsize;
	}

	public void doZoom(int percent){
		if(percent == 0)
			percent = 1;

		zoomfactor = (percent/100d);
	}

}
